package com.test.demo.mydubbo.framework.protocol.dubbo;

import com.test.demo.mydubbo.framework.protocol.DataFormater;
import com.test.demo.mydubbo.framework.protocol.URL;
import com.test.demo.mydubbo.framework.protocol.dubbo.coder.DataFormaterEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NettyClient {

    private ExecutorService executorService = Executors.newCachedThreadPool();
    public String send(URL url, DataFormater dataFormater){

        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            final NettyClientHandler client = new NettyClientHandler();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new DataFormaterEncoder());
                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(client);
                }
            });
            ChannelFuture future = bootstrap.connect(url.getHost(), url.getPort()).sync();
            //发送传输数据
//            future.channel().writeAndFlush(dataFormater);
//            future.await();

            client.setDataFormater(dataFormater);
            //future.channel().closeFuture().sync();
            //返回结果
            return executorService.submit(client).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
